package be.groept.ace.enquete.utils;

import java.io.IOException;
import java.util.SortedSet;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import be.groept.ace.enquete.beans.Link;

public class ServletUtils {
	//private static Logger logger = Logger.getLogger(ServletUtils.class);
	public static DataSource getDataSource() throws NamingException {
		Context initContext = new InitialContext();
		Context envContext = (Context) initContext.lookup("java:/comp/env");
		return (DataSource) envContext.lookup("jdbc/enquete");
	}

	public static boolean isNullOrEmpty(String value) {
		return value == null || value.trim().equals("");
	}
	
	public static void setPageTemplateSettings(
			HttpServletRequest request, 
			String title, 
			String contentpage, 
			boolean admin, 
			SortedSet<Link> headerLinks, 
			SortedSet<Link> navigationLinks) {
		request.setAttribute("title", title);
		request.setAttribute("content", contentpage);
		request.setAttribute("permission", admin ? "admin" : "user");
		request.setAttribute("headerLinks", headerLinks);
		request.setAttribute("navigationLinks", navigationLinks);
	}
	
	public static void setFormTemplateSettings(
			HttpServletRequest request, 
			String title, 
			String contentpage, 
			boolean admin, 
			SortedSet<Link> headerLinks, 
			SortedSet<Link> navigationLinks,
			String actionurl) {
		request.setAttribute("title", title);
		request.setAttribute("content", contentpage);
		request.setAttribute("permission", admin ? "admin" : "user");
		request.setAttribute("headerLinks", headerLinks);
		request.setAttribute("navigationLinks", navigationLinks);
		request.setAttribute("actionurl", actionurl);
	}
	
	public static void gotoTemplatePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		gotoPage("/WEB-INF/pages/common/template.jsp", request, response);
	}
	
	public static void gotoFormTemplatePage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		gotoPage("/WEB-INF/pages/common/template-form.jsp", request, response);
	}
	
	public static void gotoPage(String address, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.getRequestDispatcher(response.encodeURL(address)).forward(request, response);
	}
	
}
